package com.hyf.okhttp3demo.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.hyf.okhttp3demo.Config;
import com.hyf.okhttp3demo.R;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class PostJsonActivity extends AppCompatActivity {

    private Button mButton;
    private TextView mTextView;

    private OkHttpClient mOkHttpClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_json);
        mButton = (Button) findViewById(R.id.btn_sendjson);
        mTextView = (TextView) findViewById(R.id.tv_result);
        mOkHttpClient = new OkHttpClient();
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), "{\"code\":200,\"msg\":\"success\",\"passWord\":\"123456\",\"userName\":\"张三\"}");
                Request request = new Request.Builder()
                        .url(Config.API.URL_POST_JSON)
                        .post(body)
                        .build();
                mOkHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        updateUi(e.getLocalizedMessage());
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        updateUi(response.body().string());
                    }
                });
            }
        });
    }


    private void updateUi(final String result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mTextView.setText(result);
            }
        });
    }
}
